package io.sundial.conversion.impl;

import io.sundial.conversion.Converter;
import io.sundial.conversion.exception.DeserializeException;
import io.sundial.conversion.exception.SerializeException;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * Java 原生提供的转换实现
 *
 * @author Payne 646742615@qq.com
 * 2018/12/24 15:34
 */
public class JavaConverter implements Converter {

    @Override
    public String getContentType() {
        return "application/x-java-serialized-object";
    }

    @Override
    public byte[] serialize(Object obj) throws SerializeException {
        try (
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                ObjectOutputStream oos = new ObjectOutputStream(bos)
        ) {
            oos.writeObject(obj);
            oos.flush();
            return bos.toByteArray();
        } catch (Exception e) {
            throw new SerializeException(e);
        }
    }

    @Override
    public <T> T deserialize(byte[] data, Class<T> type) throws DeserializeException {
        try (
                ByteArrayInputStream bis = new ByteArrayInputStream(data);
                ObjectInputStream ois = new ObjectInputStream(bis)
        ) {
            Object obj = ois.readObject();
            return type.cast(obj);
        } catch (Exception e) {
            throw new DeserializeException(e);
        }
    }
}
